package com.doeis.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
 * 加密工具类
 * @author wangjinzhong
 * 
 */
public class Encrypt {
	/**
	 * SHA-1 算法加密字符串
	 * @param strSrc 要加密的字符串
	 * @return 加密后的字符串
	 */
	public static String sha_1(String strSrc){
		return encrypt(strSrc,"SHA-1");
	}
	/** 
	 * 字符串加密
	 * @param strSrc 要加密的字符串
	 * @param encName 加密的类型,such as: "MD5","SHA-1","SHA-256",default "MD5"
	 * @return 加密后的字符串
	 */
	public static String encrypt(String strSrc, String encName) {
		//得到MessageDigest对象
		MessageDigest md = null;
		//加密后的字符串
		String strDes = null;
		//要加密的字符串字节型数组
		byte[] bt = strSrc.getBytes();
		try {
			if (encName == null || encName.equals("")) {
				encName = "MD5";
			}
			md = MessageDigest.getInstance(encName);
			md.update(bt);
			//通过执行诸如填充之类的最终操作完成哈希计算
			strDes = bytes2Hex(md.digest()); //to HexString
		} catch (NoSuchAlgorithmException e) {
			System.out.println("Invalid algorithm.\n" + e.getMessage());
			return null;
		}
		return strDes;
	}
	/**
	 * byte to hexString
	 * @param bts
	 * @return
	 */
	private static String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
	
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}	
}
